﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.WebControls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CNRSccp.Claims.DAO;
using System.DirectoryServices;
using CNRSccp.Claims.Helper;
using System.Web;

namespace CNRSccp.Claims
{
	public class ClaimProvider_mas : SPClaimProvider
	{
		#region Members & Properties
		protected List<string> _ClaimTypeKeyList = new List<string>();
		protected string _TypeKeyLDAP = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
		protected string _TypeKeyExt = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress";
		protected string LBL_PROVIDER_NODE_KEY_EXTERN = "emailaddressext";
		protected string LBL_PROVIDER_NODE_KEY_LDAP = "emailaddress";
		protected string LBL_PROVIDER_NODE_NAME_EXTERN = "Externe";
		protected string LBL_PROVIDER_NODE_NAME_LDAP = "LDAP";
		public const string PROVIDER_DISPLAY_NAME = "CNRS Claim Provider";
		public virtual string ProviderDisplayName
		{
			get { return PROVIDER_DISPLAY_NAME; }
		}
		public const string PROVIDER_INTERNAL_NAME = "CNRSClaimProvider";
		public virtual string ProviderInternalName
		{
			get { return PROVIDER_INTERNAL_NAME; }
		}

		private const string CNRSccp_CLAIM_VALUE_TYPE = Microsoft.IdentityModel.Claims.ClaimValueTypes.String;

		// staticaly attached to the uls logging call
		//public static string CNRSClaimProviderUlsCategory = "CNRSClaimProvider";

		private string _DatabaseConnectionString;
		private string _LdapTableName = "LDAP";
		private string _ClaimsTableName = "CLAIMS";
		private string _ClaimsElementTableName = "CLAIMSELEMENT";

		private string _TokenIssuerName = string.Empty;		// the trusted token issuer Name
		private List<LdapDbConfigEntity> _LstLdapDbConfigEntity = null;
		private List<ClaimDbConfigEntity> _LstClaimDbConfigEntity = null;
		private List<ClaimsElement> _LstClaimElementEntity = null;
		private Dictionary<string, bool> _IgnoredWebApps = new Dictionary<string, bool>();

		/// <summary>
		/// Name of the SPTrustedLoginProvider associated with the claim provider
		/// </summary>
		protected SPTrustedLoginProvider AssociatedSPTrustedLoginProvider;

		protected ClaimProviderConfig CNRSccpConfig;
		
		/// <summary>
		/// Type du Claims de retour (string)
		/// </summary>
		private static string CNRSClaimValueType
		{
			get
			{
				return Microsoft.IdentityModel.Claims.ClaimValueTypes.String;
			}
		}
		public override string Name
		{
			get
			{
				return PROVIDER_INTERNAL_NAME;
			}
		}

		public override bool SupportsEntityInformation
		{
			get { return false; }
		}

		public override bool SupportsHierarchy
		{
			get { return true; }
		}

		/// <summary>
		/// Tells that CRNSccp suports Resolve
		/// </summary>
		public override bool SupportsResolve
		{
			get { return true; }
		}

		/// <summary>
		/// Tells that CNRSccp supports search
		/// </summary>
		public override bool SupportsSearch
		{
			get
			{
				return true;
			}
		}
		#endregion


		#region Constructor
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="displayName"></param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
		public ClaimProvider_mas(string displayName)
			: base(displayName)
		{
			CNRSccpConfig = ClaimProviderConfig.GetDefaultSettings(new ClaimProviderConfig());
			ClaimsHelper_mas.LogToULS(
				String.Format("[{0}] Constructor called", PROVIDER_INTERNAL_NAME),
				TraceSeverity.Verbose,
				EventSeverity.Information);
		}

		/// <summary>
		/// Initializes claim provider by loading the configuration data 
		/// This method is reserved for internal use and is not intended to be called from external code or changed
		/// </summary>
		/// <remarks>
		/// jmt-11feb2015: In a trial to be as felxibale as possible set configuration at the collection, the web application 
		///     and / or the farm. The algorithm is simple, firts look at the collection level, if not found we load 
		///     the webApp level and last but not least the farm level in a specific folder within a file.
		/// </remarks>
		protected void Initialize()
		{
			if (!_ClaimTypeKeyList.Contains(_TypeKeyLDAP))
				_ClaimTypeKeyList.Add(_TypeKeyLDAP);

			AssociatedSPTrustedLoginProvider = GetSPTrustAssociatedWithCP(PROVIDER_INTERNAL_NAME);
			if (AssociatedSPTrustedLoginProvider != null)
			{
				// Load the default farm configuration
				this._TokenIssuerName = FarmConfig.Instance.ADFSReference;
				this._DatabaseConnectionString = FarmConfig.Instance.ConnectionString;
				this._LstLdapDbConfigEntity = FarmConfig.Instance.LstLdapConfig;
				this._LstClaimElementEntity = FarmConfig.Instance.ClaimsElements;

				/* to be redone
				CNRSccpConfig = ClaimProviderConfig.GetFromConfigDB;
				if (CNRSccpConfig == null)
				{
					// Create a fake persisted object just to get the default settings, it will not be saved in config database
					// TODO: this should not happen unless CNRSccp has been configured. 
					// In this case we spould not do anything and fall back to OOTB claims provider
					// TODO: add entry in the event log

					CNRSccpConfig = ClaimProviderConfig.GetDefaultSettings(new ClaimProviderConfig());
					ClaimsHelper.LogToULS(
						String.Format("[{0}] No CNRSccpConfig PersistedObject found in the config database", ProviderInternalName),
						TraceSeverity.Medium,
						EventSeverity.Information);
				}

				SPWeb web = SPContext.Current.Site.RootWeb;
				string key = "ClaimDbConfig";
				string databaseName = string.Empty;
				if (web.Properties.ContainsKey(key))
				{
					databaseName = web.Properties[key];
					// Initialize settings from persisted object
					this._DatabaseConnectionString = string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", CNRSccpConfig.DatabaseServer, databaseName, CNRSccpConfig.DatabaseUserName, CNRSccpConfig.DatabasePassword);
					_LstLdapDbConfigEntity = SQLConfig.GetLdapDatabaseConfig(_DatabaseConnectionString, _LdapTableName);
					_LstClaimDbConfigEntity = SQLConfig.GetClaimsDatabaseConfig(_DatabaseConnectionString, _ClaimsTableName);
					_LstClaimElementEntity = SQLConfig.GetClaimsElementDatabaseConfig(_DatabaseConnectionString, _ClaimsElementTableName);
				}
				else
				{
					ClaimsHelper.LogToULS("Root Site Web does not contain any claims configuration property", TraceSeverity.Unexpected, EventSeverity.Warning);
				}
				 * 
				 * */
			}
		}

		/// <summary>
		/// Get the first TrustedLoginProvider associated with current claim provider
		/// LIMITATION: The same claims provider (uniquely identified by its name) cannot be associated to multiple TrustedLoginProvider because at runtime there is no way to determine what TrustedLoginProvider is currently calling
		/// </summary>
		/// <param name="ProviderInternalName"></param>
		/// <returns></returns>
		public static SPTrustedLoginProvider GetSPTrustAssociatedWithCP(string ProviderInternalName)
		{
			var lp = SPSecurityTokenServiceManager.Local.TrustedLoginProviders.Where(x => String.Equals(x.ClaimProviderName, ProviderInternalName, StringComparison.OrdinalIgnoreCase));

			if (lp != null && lp.Count() == 1)
				return lp.First();

			if (lp != null && lp.Count() > 1)
				ClaimsHelper_mas.LogToULS(String.Format("[{0}] Claims provider is associated to multiple TrustedLoginProvider, which is not supported because at runtime there is no way to determine what TrustedLoginProvider is currently calling", ProviderInternalName), TraceSeverity.Unexpected, EventSeverity.Error);

			ClaimsHelper_mas.LogToULS(String.Format("[{0}] Claims provider {1} is not associated with any SPTrustedLoginProvider, so it cannot create permissions.\r\nVisit http://ldapcp.codeplex.com for installation procedure or set property ClaimProviderName with PowerShell cmdlet Get-SPTrustedIdentityTokenIssuer to create association.", ProviderInternalName, ProviderInternalName), TraceSeverity.Unexpected, EventSeverity.Warning);

			return null;
		}
		#endregion

		#region Methods
		#region Claims configuration methods
		/// <summary>
		/// Méthode utilisée pour de l'augmentation Claims
		/// </summary>
		/// <param name="context"></param>
		/// <param name="entity"></param>
		/// <param name="claims"></param>
		protected override void FillClaimsForEntity(Uri context, SPClaim entity, List<SPClaim> claims)
		{
			if (entity == null)
				throw new ArgumentNullException("entity");

			if (claims == null)
				throw new ArgumentNullException("claims");
		}

		/// <summary>
		/// Spécifie les types de Claim à récupérer
		/// </summary>
		/// <param name="claimTypes"></param>
		protected override void FillClaimTypes(List<string> claimTypes)
		{
			if (claimTypes == null)
				throw new ArgumentNullException("claimTypes");

			foreach (string typeKey in _ClaimTypeKeyList)
			{
				//Add our claim type.
				claimTypes.Add(typeKey);
			}
		}

		/// <summary>
		/// Add our claim value type (string)
		/// </summary>
		/// <param name="claimValueTypes"></param>
		protected override void FillClaimValueTypes(List<string> claimValueTypes)
		{
			if (claimValueTypes == null)
				throw new ArgumentNullException("claimValueTypes");

			//Add our claim value type.
			claimValueTypes.Add(CNRSccp_CLAIM_VALUE_TYPE);
		}

		/// <summary>
		/// Précise les types d'entités à récupérer
		/// </summary>
		/// <param name="entityTypes"></param>
		protected override void FillEntityTypes(List<string> entityTypes)
		{
			//Return the type of entity claim we are using
			entityTypes.Add(SPClaimEntityTypes.FormsRole);
			entityTypes.Add(SPClaimEntityTypes.User);
		}
		#endregion

		#region Provisionning hierarchy methods (People Picker)
		/// <summary>
		/// Méthode de approvisionnement de l'arborescence
		/// </summary>
		/// <param name="context"></param>
		/// <param name="entityTypes"></param>
		/// <param name="hierarchyNodeID"></param>
		/// <param name="numberOfLevels"></param>
		/// <param name="hierarchy"></param>
		protected override void FillHierarchy(Uri context, string[] entityTypes, string hierarchyNodeID, int numberOfLevels, SPProviderHierarchyTree hierarchy)
		{
			//On ne récupère que les Users ou les Roles
			if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole) && !EntityTypesContain(entityTypes, SPClaimEntityTypes.User))
				return;

			//Check to see if the hierarchyNodeID is null; it will be when the control 
			//is first loaded but if a user clicks on one of the nodes it will return
			//the key of the node that was clicked.
			switch (hierarchyNodeID)
			{
				//Pas de click
				case null:
					FillHierarchyAction(hierarchy);
					break;
				default:
					break;
			}
		}

		/// <summary>
		/// Méthode de approvisionnement du contenu de l'arborescence (les différents claims)
		/// </summary>
		/// <param name="site"></param>
		/// <param name="hierarchy"></param>
		private void FillHierarchyAction(SPProviderHierarchyTree hierarchy)
		{
			Initialize(); //merged from sp6
			//Chargement branche LDAP
			hierarchy.AddChild(new
				SPProviderHierarchyNode(
						PROVIDER_INTERNAL_NAME,
						LBL_PROVIDER_NODE_NAME_LDAP,
						LBL_PROVIDER_NODE_KEY_LDAP,
						true));
			if (!_ClaimTypeKeyList.Contains(_TypeKeyLDAP))
				_ClaimTypeKeyList.Add(_TypeKeyLDAP);

			//Chargement branche Externe
			hierarchy.AddChild(new
				SPProviderHierarchyNode(
						PROVIDER_INTERNAL_NAME,
						LBL_PROVIDER_NODE_NAME_EXTERN,
						LBL_PROVIDER_NODE_KEY_EXTERN,
						true));
			if (!_ClaimTypeKeyList.Contains(_TypeKeyExt))
				_ClaimTypeKeyList.Add(_TypeKeyExt);

			//Chargement des Claims
			//if (SPContext.Current != null && !TestIgnoredWebApps(SPContext.Current.Web.Url))
			//{
				List<ClaimsElement> claimsElements = _LstClaimElementEntity;
				if (claimsElements != null && claimsElements.Count > 0)
				{
					foreach (ClaimsElement claimElement in claimsElements)
					{
						if (!claimElement.Hidden)
						{
							//Fill claim typeKey list
							string typeKey = claimElement.Type + claimElement.ClaimKey;
							if (!_ClaimTypeKeyList.Contains(typeKey))
								_ClaimTypeKeyList.Add(typeKey);

							hierarchy.AddChild(new
								SPProviderHierarchyNode(
									 PROVIDER_INTERNAL_NAME,
									 claimElement.Title,
									 claimElement.ClaimKey,
									 true));
						}
					}
				//}
			}
		}
		#endregion

		#region Search methods inside People Picker
		/// <summary>
		/// Recherche d'abord dans les utilisateurs LDAP, puis Externe, puis les DB SQL
		/// </summary>
		/// <param name="context"></param>
		/// <param name="entityTypes"></param>
		/// <param name="searchPattern"></param>
		/// <param name="hierarchyNodeID"></param>
		/// <param name="maxCount"></param>
		/// <param name="searchTree"></param>
		protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree)
		{
			Initialize();
			//La recherche s'effectue sans le code Claims, on le retire s'il existe.
			searchPattern = ClaimsHelper_mas.GetDecodedClaim(searchPattern, true);

			//On ne récupère que les Users ou les Roles
			if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole) && !EntityTypesContain(entityTypes, SPClaimEntityTypes.User))
				return;

			//Arborescence de recherche
			SPProviderHierarchyNode matchNode = null;

			#region Test LDAP
			List<string> results = LdapHelper_mas.FindMailInLDAP(searchPattern.ToLower(), _LstLdapDbConfigEntity);
			if (results != null && results.Count > 0)
			{
				//Same sort of code as in search to validate we have a match.
				foreach (string mail in results)
				{
					//We have a match, create a matching entity.
					PickerEntity pe = GetPickerEntity(_TypeKeyLDAP, mail);

					//Add the term node where it should be displayed too.
					if (!searchTree.HasChild("emailaddress"))
					{
						//Create the node so we can show our match in there too.
						matchNode = new SPProviderHierarchyNode(PROVIDER_INTERNAL_NAME, LBL_PROVIDER_NODE_NAME_LDAP, LBL_PROVIDER_NODE_KEY_LDAP, true);

						//Add it to the tree.
						searchTree.AddChild(matchNode);
					}
					else
						//Get the node for this term.
						matchNode = searchTree.Children.Where(theNode => theNode.HierarchyNodeID == LBL_PROVIDER_NODE_KEY_LDAP).First();

					//Add the match to our node.
					matchNode.AddEntity(pe);
				}
				return;
			}
			#endregion

			#region Test Externe User
			if (ClaimsHelper_mas.CheckEmail(searchPattern.ToLower()))
			{
				//We have a match, create a matching entity.
				string lowerSearch = searchPattern.ToLower();
				PickerEntity pe = GetPickerEntity(_TypeKeyLDAP, lowerSearch);

				//Add the term node where it should be displayed too.
				if (!searchTree.HasChild(LBL_PROVIDER_NODE_KEY_EXTERN))
				{
					//Create the node so we can show our match in there too.
					matchNode = new
						SPProviderHierarchyNode(ClaimProvider_mas.PROVIDER_INTERNAL_NAME,
						LBL_PROVIDER_NODE_NAME_EXTERN,
						LBL_PROVIDER_NODE_KEY_EXTERN,
						true);

					//Add it to the tree.
					searchTree.AddChild(matchNode);
				}
				else
					//Get the node for this term.
					matchNode = searchTree.Children.Where(theNode => theNode.HierarchyNodeID == LBL_PROVIDER_NODE_KEY_EXTERN).First();

				//Add the match to our node.
				matchNode.AddEntity(pe);
				return;
			}
			#endregion

			#region Test DB List
			//SPContext.Current.Web.Url.Contains(Constantes.WEBAPPLICATION_CENTRALE_ADMIN_REF_URL) - permits to disable this part of code for the central admin
			//if (SPContext.Current != null
			//    && !TestIgnoredWebApps(SPContext.Current.Web.Url))
			//{
			//    FillSearchDatabase(searchPattern, searchTree, hierarchyNodeID, matchNode);
			//}
			FillSearchDatabase(searchPattern, searchTree, hierarchyNodeID, matchNode);
			#endregion
		}

		/// <summary>
		/// Construction de l'arborescence de résultats
		/// </summary>
		/// <param name="searchPattern"></param>
		/// <param name="searchTree"></param>
		/// <param name="hierarchyNodeID"></param>
		/// <param name="matchNode"></param>
		private void FillSearchDatabase(string searchPattern, SPProviderHierarchyTree searchTree, string hierarchyNodeID, SPProviderHierarchyNode matchNode)
		{
			List<ClaimsElement> claimsElements = _LstClaimElementEntity;
			if (claimsElements != null && claimsElements.Count > 0)
			{
				//Si node préselectionnée
				if (hierarchyNodeID != null)
				{
					foreach (ClaimsElement claimElement in claimsElements)
					{
						if (!claimElement.Hidden)
						{
							//If the user have preselected a node
							if (!string.IsNullOrEmpty(claimElement.ClaimKey)
								&& claimElement.ClaimKey == hierarchyNodeID)
							{
								AddMatchNode(searchPattern, matchNode, searchTree, claimElement);
								break;
							}
						}
					}
				}
				else
				{
					foreach (ClaimsElement claimElement in claimsElements)
					{
						if (!claimElement.Hidden)
						{
							AddMatchNode(searchPattern, matchNode, searchTree, claimElement);
						}
					}
				}
			}
		}

		/// <summary>
		/// Search in a particular node RefList to found a match
		/// </summary>
		/// <param name="currentWeb"></param>
		/// <param name="searchPattern"></param>
		/// <param name="matchNode"></param>
		/// <param name="searchTree"></param>
		/// <param name="node"></param>
		private void AddMatchNode(string searchPattern, SPProviderHierarchyNode matchNode, SPProviderHierarchyTree searchTree, ClaimsElement element)
		{
			string typeKey = element.Type + element.ClaimKey;
			string nodeID = element.ClaimKey;
			string nodeLabel = element.Title;
			string nodeListRefName = element.DB; //Database ou vue à utiliser
			string nodeListRefID = element.ReferenceID; //Champs SQL à utiliser
			if (_LstClaimDbConfigEntity != null && _LstClaimDbConfigEntity.Count > 0)
			{
				List<DataElement> dataElements = new List<DataElement>();
				foreach (ClaimDbConfigEntity claimDbConfigEntity in _LstClaimDbConfigEntity)
				{
					BaseDAO_mas daoList = new BaseDAO_mas(claimDbConfigEntity.ConnectionString, nodeListRefName);
					if (!string.IsNullOrEmpty(searchPattern))
					{
						DAOParameter parameter = new DAOParameter() { Column = nodeListRefID, ParameterName = "@" + nodeListRefID, Value = searchPattern };
						List<DataElement> dataElements2 = daoList.GetItems(parameter);
						dataElements.AddRange(dataElements2);
					}
				}
				if (dataElements.Count > 0)
				{
					//Look to see if the value that is typed in matches any of our terms.
					foreach (DataElement dataElement in dataElements)
					{
						//We have a match, create a matching entity.
						PickerEntity pe = GetPickerEntity(typeKey, string.Format(element.Format, dataElement.Value), string.Format(element.FormatDisplay, dataElement.Value));

						//Add the term node where it should be displayed too.
						if (!searchTree.HasChild(nodeID))
						{
							//Create the node so we can show our match in there too.
							matchNode = new
								SPProviderHierarchyNode(PROVIDER_INTERNAL_NAME,
								nodeLabel,
								nodeID,
								true);

							//Add it to the tree.
							searchTree.AddChild(matchNode);
						}
						else
							//Get the node for this term.
							matchNode = searchTree.Children.Where(theNode => theNode.HierarchyNodeID == nodeID).First();

						//Add the match to our node.
						matchNode.AddEntity(pe);
					}
				}
			}
		}

		/// <summary>
		/// FillSchema
		/// </summary>
		/// <param name="schema"></param>
		protected override void FillSchema(SPProviderSchema schema)
		{
			//Add the schema element we need at a minimum in our picker node.
			schema.AddSchemaElement(new SPSchemaElement(PeopleEditorEntityDataKeys.DisplayName, "Display Name", SPSchemaElementType.Both));
		}
		#endregion

		#region Search methods outside People Picker
		/// <summary>
		/// Méthode de résolution de l'input du Provider
		/// </summary>
		/// <param name="context"></param>
		/// <param name="entityTypes"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		protected override void FillResolve(Uri context, string[] entityTypes, SPClaim resolveInput, List<PickerEntity> resolved)
		{
			//On ne récupère que les Users ou les Roles
			if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole) && !EntityTypesContain(entityTypes, SPClaimEntityTypes.User))
				return;

			SearchAndResolveEntity(context, resolveInput.Value.ToLower(), resolveInput.ClaimType, resolved);
		}

		/// <summary>
		/// Méthode de résolution de l'input du Provider
		/// </summary>
		/// <param name="context"></param>
		/// <param name="entityTypes"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List<PickerEntity> resolved)
		{
			//On ne récupère que les Users ou les Roles
			if (!EntityTypesContain(entityTypes, SPClaimEntityTypes.FormsRole) && !EntityTypesContain(entityTypes, SPClaimEntityTypes.User))
				return;

			SearchAndResolveEntity(context, resolveInput, resolved);
		}

		/// <summary>
		/// Travail de recherche sur LDAP, Externe ou Listes Unités
		/// </summary>
		/// <param name="context"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		private void SearchAndResolveEntity(Uri context, string resolveInput, List<PickerEntity> resolved)
		{
			SearchAndResolveEntity(context, resolveInput, string.Empty, resolved);
		}

		/// <summary>
		/// Travail de recherche sur LDAP, Externe ou Listes Unités
		/// </summary>
		/// <param name="context"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		private void SearchAndResolveEntity(Uri context, string resolveInput, string claimType, List<PickerEntity> resolved)
		{
			Initialize();
			try
			{
				#region LDAP
				List<string> results = LdapHelper_mas.FindMailInLDAP(resolveInput.ToLower(), _LstLdapDbConfigEntity);
				if (results != null && results.Count > 0)
				{
					//Same sort of code as in search to validate we have a match.
					foreach (string mail in results)
					{
						//We have a match, create a matching entity.
						PickerEntity pe = GetPickerEntity(_TypeKeyLDAP, mail);

						//Add it to the return list of picker entries.
						resolved.Add(pe);
					}
				}
				#endregion
				#region Test Externe User
				else
				{
					if (ClaimsHelper_mas.CheckEmail(resolveInput.ToLower()))
					{
						//We have a match, create a matching entity.
						string resolveLower = resolveInput.ToLower();
						PickerEntity pe = GetPickerEntity(_TypeKeyExt, resolveLower);

						//Add it to the return list of picker entries.
						resolved.Add(pe);
					}
				}
				SearchAndResolveEntityDatabase(resolveInput, claimType, resolved);
				#endregion
				#region Test SharePoint List
				//if (SPContext.Current != null
				//    && !TestIgnoredWebApps(SPContext.Current.Web.Url))
				//{
				//    SearchAndResolveEntityDatabase(resolveInput, claimType, resolved);
				//}
				#endregion
			}
			catch (Exception ex)
			{
				ClaimsHelper_mas.LogToULS("LDAP connexion error", TraceSeverity.Unexpected, EventSeverity.Warning);
			}
		}

		/// <summary>
		/// Travail de recherche sur listes Unités
		/// </summary>
		/// <param name="site"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		private void SearchAndResolveEntityDatabase(string resolveInput, List<PickerEntity> resolved)
		{
			SearchAndResolveEntityDatabase(resolveInput, string.Empty, resolved);
		}

		/// <summary>
		/// Travail de recherche sur listes Unités
		/// </summary>
		/// <param name="site"></param>
		/// <param name="resolveInput"></param>
		/// <param name="resolved"></param>
		private void SearchAndResolveEntityDatabase(string resolveInput, string claimType, List<PickerEntity> resolved)
		{
				if (_LstClaimDbConfigEntity != null && _LstClaimDbConfigEntity.Count > 0)
				{
					if (_LstClaimElementEntity != null && _LstClaimElementEntity.Count > 0)
					{
						foreach (ClaimsElement claimsElement in _LstClaimElementEntity)
						{
							List<DataElement> dataElements = new List<DataElement>();
							//Fill claims types list
							string typeKey = claimsElement.Type + claimsElement.ClaimKey;
							foreach (ClaimDbConfigEntity claimDbConfigEntity in _LstClaimDbConfigEntity)
							{
								if (string.IsNullOrEmpty(claimType) || typeKey.ToLower() == claimType.ToLower())
								{
									if (!_ClaimTypeKeyList.Contains(typeKey))
										_ClaimTypeKeyList.Add(typeKey);

									BaseDAO_mas daoList = new BaseDAO_mas(claimDbConfigEntity.ConnectionString, claimsElement.DB);
									if (!string.IsNullOrEmpty(resolveInput))
									{
										DAOParameter parameter = new DAOParameter() { Column = claimsElement.ReferenceID, ParameterName = "@" + claimsElement.ReferenceID, Value = resolveInput };
										List<DataElement> dataElements2 = daoList.GetItems(parameter);
										dataElements.AddRange(dataElements2);
									}
								}
							}
							if (dataElements.Count > 0)
							{
								//Look to see if the value that is typed in matches any of our terms.
								foreach (DataElement dataElement in dataElements)
								{
									PickerEntity pe = GetPickerEntity(typeKey, string.Format(claimsElement.Format, dataElement.Value), string.Format(claimsElement.FormatDisplay, dataElement.Value));

									//Add it to the return list of picker entries.
									resolved.Add(pe);
								}
							}
						}
					}
				}
		}
		#endregion

		#region Tools methods
		/// <summary>
		/// Vérifie les urls ignorées et renvoie true si le paramètre matches
		/// </summary>
		/// <param name="currentUrl"></param>
		/// <returns></returns>
		//private bool TestIgnoredWebApps(string currentUrl)
		//{
		//    if (!_IgnoredWebApps.ContainsKey(currentUrl))
		//    {
		//        List<string> ignoredWebApps = ClaimsParameters.Instance.IgnoredWebApps;

		//        foreach (string ignoredWebApp in ignoredWebApps)
		//        {
		//            if (ignoredWebApp.Contains(currentUrl))
		//            {
		//                _IgnoredWebApps.Add(currentUrl, true);
		//                return true;
		//            }
		//        }

		//        _IgnoredWebApps.Add(currentUrl, false);
		//        return false;
		//    }

		//    return _IgnoredWebApps[currentUrl];
		//}

		/// <summary>
		/// Créé un PickerEntity en fonction de son claims
		/// </summary>
		/// <param name="ClaimTypeKey"></param>
		/// <param name="ClaimValue"></param>
		/// <returns></returns>
		private PickerEntity GetPickerEntity(string ClaimTypeKey, string ClaimValue)
		{
			return GetPickerEntity(ClaimTypeKey, ClaimValue, ClaimValue);
		}

		/// <summary>
		/// Créé un PickerEntity en fonction de son claims
		/// </summary>
		/// <param name="ClaimTypeKey"></param>
		/// <param name="ClaimValue"></param>
		/// <returns></returns>
		private PickerEntity GetPickerEntity(string ClaimTypeKey, string ClaimValue, string DisplayName)
		{
			//We have a match, create a matching entity.
			PickerEntity pe = CreatePickerEntity();
			//Set the claim associated with this match.

			pe.Claim = new SPClaim(ClaimTypeKey, ClaimValue, CNRSccp_CLAIM_VALUE_TYPE, SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, _TokenIssuerName));

			//Set the tooltip that is displayed when you hover over the resolved claim.
			pe.Description = ClaimProvider_mas.PROVIDER_DISPLAY_NAME + ": " + ClaimValue + " (" + ClaimTypeKey + ")";

			//Set the text we will display.
			pe.DisplayText = DisplayName;

			//Store it here too in the hashtable **.
			pe.EntityData[PeopleEditorEntityDataKeys.DisplayName] = DisplayName;
			//pe.EntityData[PeopleEditorEntityDataKeys.Email] = "jean-marie.thia@dsi.cnrs.fr";

			//User entity.
			if (ClaimTypeKey == _TypeKeyLDAP || ClaimTypeKey == _TypeKeyExt)
				pe.EntityType = SPClaimEntityTypes.User;
			else
				pe.EntityType = SPClaimEntityTypes.FormsRole;

			//Flag the entry as being resolved.
			pe.IsResolved = true;

			//This is the first part of the description that shows
			//up above the matches, like Role: Forms Authentication when
			//you do an FBA search and find a matching role.
			pe.EntityGroupName = "CNRS term";
			return pe;
		}

		#endregion
		#endregion

	}
}
